﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Util.Extension;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    [Area("Console")]
    public class BasicSettingsController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly mtContext _context;
        public BasicSettingsController(mtContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region 电汇账户
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetWireTransferListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.WireTransfers
                           select new
                           {
                               id = n.Id,
                               currencyReceipt = n.Currency,
                               payee = n.Payee,
                               payeeNumber = n.AccountNumber,
                               payeeAddress = n.PayeeAddress,
                               receivingBank = n.Bank,
                               bankAddress = n.BankAddress,
                               swiftcode = n.Swiftcode,
                               state = n.Status,
                               sort = n.Sort,
                               creator = n.Creator,
                               createDate = n.CreateDate
                           };
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToList(); ;
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }

        #region 添加
        public IActionResult CreateWireTransfe()
        {
            int? Sort = 1;
            if (_context.WireTransfers.Count() > 0)
            {
                Sort = _context.WireTransfers.Max(k => k.Sort) + 1;
            }
            ViewBag.Sort = Sort;
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateWireTransfe(WireTransfer model)
        {
            Result res = new Result();
            try
            {
                if (!ToWireTransferExists(model.AccountNumber))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTime.Now;
                    model.Currency = "USD";
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.ToString();
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑信息
        public async Task<IActionResult> EditWireTransfe(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            WireTransfer data = await _context.WireTransfers.FindAsync(id);
            if (data == null)
            {
                return NotFound();
            }
            return View(data);
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditWireTransfe(WireTransfer item)
        {
            Result res = new Result();
            try
            {
                if (!ToWireTransferExists(item.AccountNumber, item.Id))
                {
                    WireTransfer model = await _context.WireTransfers.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.Currency = item.Currency;
                        model.Payee = item.Payee;
                        model.PayeeAddress = item.PayeeAddress;
                        model.AccountNumber = item.AccountNumber;
                        model.Bank = item.Bank;
                        model.BankAddress = item.BankAddress;
                        model.Swiftcode = item.Swiftcode;
                        model.Status = item.Status;
                        model.Sort = item.Sort;
                        model.Minimum = item.Minimum;
                        model.Maximum = item.Maximum;
                        model.RoleId = item.RoleId;
                        model.Qrcode = item.Qrcode;
                        model.Remark = item.Remark;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateWireTransferState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                WireTransfer data = await _context.WireTransfers.FindAsync(id);

                data.Status = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteWireTransfer")]
        public async Task<JsonResult> DeleteWireTransfer(int id)
        {
            Result res = new Result();
            try
            {
                WireTransfer data = await _context.WireTransfers.FindAsync(id);

                _context.WireTransfers.Remove(data);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="WireTransfers">账号</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        private bool ToWireTransferExists(string AccountNumber, int id = 0)
        {
            if (id == 0)
                return _context.WireTransfers.Any(e => e.AccountNumber == AccountNumber);
            else
                return _context.WireTransfers.Any(e => e.Id != id && e.AccountNumber == AccountNumber);
        }
        #endregion

        #endregion

        #region 汇款账户
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetRemittanceAccountListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.RemittanceAccounts
                           select new
                           {
                               id = n.Id,
                               currencyReceipt = n.Currency,
                               accountName = n.Payee,
                               accountNumber = n.AccountNumber,
                               bank = n.Bank,
                               branchName = n.BranchName,
                               state = n.Status,
                               sort = n.Sort,
                               qrcode = n.Qrcode,
                               creator = n.Creator,
                               createDate = n.CreateDate
                           };
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToList(); ;
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }

        #region 添加
        public IActionResult CreateRemittanceAccount()
        {
            int? Sort = 1;
            if (_context.RemittanceAccounts.Count() > 0)
            {
                Sort = _context.RemittanceAccounts.Max(k => k.Sort) + 1;
            }
            ViewBag.Sort = Sort;

            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateRemittanceAccount(RemittanceAccount model)
        {
            Result res = new Result();
            try
            {
                if (!ToRemittanceAccountExists(model.AccountNumber))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTime.Now;
                    model.Currency = "USD";
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑信息
        public async Task<IActionResult> EditRemittanceAccount(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            RemittanceAccount data = await _context.RemittanceAccounts.FindAsync(id);
            if (data == null)
            {
                return NotFound();
            }
            return View(data);
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditRemittanceAccount(RemittanceAccount item)
        {
            Result res = new Result();
            try
            {
                if (!ToRemittanceAccountExists(item.AccountNumber, item.Id))
                {
                    RemittanceAccount model = await _context.RemittanceAccounts.FindAsync(item.Id);
                    if (model != null)
                    {
                        //model.Currency = item.Currency;
                        model.Payee = item.Payee;
                        model.AccountNumber = item.AccountNumber;
                        model.Bank = item.Bank;
                        model.BranchName = item.BranchName;
                        model.Status = item.Status;
                        model.Sort = item.Sort;
                        model.Minimum = item.Minimum;
                        model.Maximum = item.Maximum;
                        model.RoleId = item.RoleId;
                        model.Qrcode = item.Qrcode;
                        model.Remark = item.Remark;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateRemittanceAccountState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                RemittanceAccount data = await _context.RemittanceAccounts.FindAsync(id);

                data.Status = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteRemittanceAccount")]
        public async Task<JsonResult> DeleteRemittanceAccount(int id)
        {
            Result res = new Result();
            try
            {
                RemittanceAccount data = await _context.RemittanceAccounts.FindAsync(id);

                _context.RemittanceAccounts.Remove(data);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="RemittanceAccounts">账号</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        private bool ToRemittanceAccountExists(string AccountNumber, int id = 0)
        {
            if (id == 0)
                return _context.RemittanceAccounts.Any(e => e.AccountNumber == AccountNumber);
            else
                return _context.RemittanceAccounts.Any(e => e.Id != id && e.AccountNumber == AccountNumber);
        }
        #endregion

        #endregion

        #region 加密货币地址
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetCryptocurrencyListJson(int page, int limit)
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.Cryptocurrencies
                           select new
                           {
                               id = n.Id,
                               currencyReceipt = n.Currency,
                               network = n.Network,
                               receivingAddress = n.ReceivingAddress,
                               state = n.Status,
                               sort = n.Sort,
                               creator = n.Creator,
                               createDate = n.CreateDate
                           };
                res.Code = 0;
                res.Count = data.Count();
                res.Data = data.OrderBy(k => k.id).Skip((page - 1) * limit).Take(limit).ToList(); ;
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
            }
            return new JsonResult(res);
        }

        #region 添加
        public IActionResult CreateCryptocurrency()
        {
            int? Sort = 1;
            if (_context.Cryptocurrencies.Count() > 0)
            {
                Sort = _context.Cryptocurrencies.Max(k => k.Sort) + 1;
            }
            ViewBag.Sort = Sort;
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> CreateCryptocurrency(Cryptocurrency model)
        {
            Result res = new Result();
            try
            {
                if (!ToCryptocurrencyExists(model.Network, model.ReceivingAddress))
                {
                    model.Creator = User.LoginName;
                    model.CreateDate = DateTime.Now;
                    _context.Add(model);
                    res.Code = 0;
                    res.Data = await _context.SaveChangesAsync();
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 编辑信息
        public async Task<IActionResult> EditCryptocurrency(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            Cryptocurrency data = await _context.Cryptocurrencies.FindAsync(id);
            if (data == null)
            {
                return NotFound();
            }
            return View(data);
        }
        /// <summary>
        /// 编辑信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> EditCryptocurrency(Cryptocurrency item)
        {
            Result res = new Result();
            try
            {
                if (!ToCryptocurrencyExists(item.Network, item.ReceivingAddress, item.Id))
                {
                    Cryptocurrency model = await _context.Cryptocurrencies.FindAsync(item.Id);
                    if (model != null)
                    {
                        model.Currency = item.Currency;
                        model.Network = item.Network;
                        model.ReceivingAddress = item.ReceivingAddress;
                        model.Status = item.Status;
                        model.Sort = item.Sort;
                        model.Minimum = item.Minimum;
                        model.Maximum = item.Maximum;
                        model.RoleId = item.RoleId;
                        model.Remark = item.Remark;
                        res.Code = 0;
                        res.Data = await _context.SaveChangesAsync();
                    }
                    else
                    {
                        res.Code = 1;
                        res.Msg = "submitFail";
                    }
                }
                else
                {
                    res.Code = 1;
                    res.Msg = "accountExists";
                }
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = "submitFail";
                res.Data = ex.Message;
                return new JsonResult(res);
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpdateCryptocurrencyState(int id, int intState)
        {
            ListResult res = new ListResult();
            try
            {
                Cryptocurrency data = await _context.Cryptocurrencies.FindAsync(id);

                data.Status = intState;
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除单个
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost, ActionName("DeleteCryptocurrency")]
        public async Task<JsonResult> DeleteCryptocurrency(int id)
        {
            Result res = new Result();
            try
            {
                Cryptocurrency data = await _context.Cryptocurrencies.FindAsync(id);

                _context.Cryptocurrencies.Remove(data);
                res.Code = 0;
                res.Data = await _context.SaveChangesAsync();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }
        #endregion

        #region 判断是否存在
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="Cryptocurrencys">账号</param>
        /// <param name="id">ID</param>
        /// <returns></returns>
        private bool ToCryptocurrencyExists(string Network, string ReceivingAddress, int id = 0)
        {
            if (id == 0)
                return _context.Cryptocurrencies.Any(e => e.Network == Network && e.ReceivingAddress == ReceivingAddress);
            else
                return _context.Cryptocurrencies.Any(e => e.Id != id && e.Network == Network && e.ReceivingAddress == ReceivingAddress);
        }
        #endregion

        #endregion
    }
}
